// 示例代码：通过脚本应用高度图
using UnityEngine;
using UnityEditor;

[ExecuteAlways]
public class ApplyHeightmap : MonoBehaviour
{
    public Texture2D heightMap;
    public Terrain terrain;
    
    void Start()
    {
        if (terrain == null)
            terrain = GetComponent<Terrain>();
            
        if (heightMap != null)
        {
            int width = heightMap.width;
            int height = heightMap.height;
            float[,] heights = new float[width, height];
            
            // 将图像数据转换为高度数据
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    Color pixel = heightMap.GetPixel(x, y);
                    // 使用灰度值作为高度
                    heights[x, y] = pixel.grayscale;
                }
            }
            
            // 设置地形高度
            terrain.terrainData.SetHeights(0, 0, heights);
        }
    }
}